/* eslint-disable prefer-destructuring */
import React, { Component } from 'react';
import { Menu, Icon } from 'antd';
import styles from './ToolBar.less';
import * as commonConfig from '../../../utils/config';
import * as commonUtils from '../../../utils/utils';
// import * as commonFunc from '../commonFunc'; /* 通用单据方法 */
import AffixMenu from '../../../routes/common/AffixMenu';

const { SubMenu } = Menu;
const MenuItemGroup = Menu.ItemGroup;

class ToolBarComponent extends Component {
  /**   构造函数   */
  constructor(props) {
    super(props);
    this.state = {
      menuData: [], /* 导航工具栏 */
      enabled: false,
      bCheck: false,
      bInvalid: false,
    };
  }

  componentWillMount() {
    this.componentWillReceiveProps(this.props);
  }
  /**   props改变的时候触发   */
  componentWillReceiveProps(nextProps) {
    /* nextprops变化引起的菜单变化集合 */
    const {
      masterConfig, gdsjurisdiction, report, masterData,
    } = nextProps;
    let {
      menuData, searchUpDownData, enabled, bCheck, bInvalid,
    } = this.state;
    const btnShowData = [...commonConfig.btnData];
    if (commonUtils.isNotEmptyObject(masterConfig) && commonUtils.isEmptyArr(menuData)) {
      const buttonConfig = masterConfig.gdsconfigformslave.filter(item => item.sName === '' && item.showName !== '' && item.sControlName !== '');
      /** 筛选出显示的按钮 */
      buttonConfig.forEach((child) => {
        if (child.bVisible && child.sControlName.substring(0, 3) === 'Btn' && btnShowData.findIndex(item => item.sControlName === child.sControlName) === -1) {
          child.iconName = 'menu-unfold';
          btnShowData.push(child);
        }
        const index = btnShowData.findIndex(item => item.sControlName === child.sControlName && !child.bVisible);
        if (index > -1) {
          btnShowData.splice(index, 1);
        }
      });

      /** 根据权限，筛选出显示的按钮  */
      gdsjurisdiction.forEach((child) => {
        const index = btnShowData.findIndex(item => item.sControlName === child.sAction);
        if (index > -1) {
          btnShowData.splice(index, 1);
        }
      });


      /*  筛选出一级菜单    */
      menuData = btnShowData.filter(item => !item.sControlName.includes('.'));
      /*  初始值的二级菜单    */
      // const secondMenu = btnShowData.filter(item => item.sControlName.includes('.'));
      /** 配置后匹配二级菜单 */
      menuData.forEach((menu) => {
        menu.child = [];
        /** 匹配相应的子菜单 */
        const childData = btnShowData.filter(item => item.sControlName.startsWith(`${menu.sControlName}.`) && item.sControlName.split('.').length <= 2);
        if (menu.sControlName === 'BtnPrint') {
          /*   打印的二级菜单集合   */
          const reportChild = [];
          if (commonUtils.isNotEmptyArr(report)) {
            for (const each of report) {
              reportChild.push({
                sControlName: `BtnPrint.${each.sId}`,
                showName: each.sReportName,
                disabled: false,
                sActiveId: each.sId,
                sId: each.sId,
              });
            }
          }
          menu.child.push(...reportChild);
        } else if (commonUtils.isNotEmptyArr(childData)) {
          menu.child.push(...childData);
        }
      });
    }
    if (enabled !== nextProps.enabled) {
      enabled = nextProps.enabled;
    }
    if (commonUtils.isNotEmptyObject(masterData) && bCheck !== masterData.bCheck) {
      bCheck = masterData.bCheck;
    }
    if (commonUtils.isNotEmptyObject(masterData) && bInvalid !== masterData.bInvalid) {
      bInvalid = masterData.bInvalid;
    }
    if (JSON.stringify(searchUpDownData) !== JSON.stringify(nextProps.searchUpDownData)) {
      searchUpDownData = nextProps.searchUpDownData;
    }
    this.setState({
      menuData, searchUpDownData, enabled, bCheck, bInvalid,
    });
  }

  shouldComponentUpdate(nextProps, nextState) {
    const { masterConfig } = nextProps;
    const {
      menuData, searchUpDownData, enabled, bCheck, bInvalid,
    } = this.state;
    const {
      adDisabled,
    } = this.props;
    return masterConfig !== undefined && Object.keys(masterConfig).length > 0 &&
      (JSON.stringify(menuData) !== JSON.stringify(nextState.menuData) ||
      JSON.stringify(searchUpDownData) !== JSON.stringify(nextState.searchUpDownData) ||
      enabled !== nextState.enabled || bCheck !== nextState.bCheck || bInvalid !== nextState.bInvalid || adDisabled !== nextProps.adDisabled);
  }

  /**   获取有三级菜单的父级菜单属性   */
  getMenuProps = (menu, type) => {
    const obj = {};
    obj.key = menu.sControlName;
    obj.disabled = this.getMenuStatus(menu);
    const { iconName, showName } = menu;
    obj.className = styles.toolBarSub;
    if (menu.sControlName !== undefined && (menu.sControlName.indexOf('BtnUpCheck') > -1 || menu.sControlName.indexOf('BtnDownCheck') > -1) && !menu.sControlName.includes('.')) {
      obj.onMouseEnter = this.handleMouseEnter; /*   根据二级菜单获取三级数据   */
    }
    obj['data-sActiveId'] = menu.sActiveId;
    if (type === 'icon') {
      obj.title = <span><Icon type={iconName} />{showName}<Icon type="down" theme="outlined" /></span>;
    } else if (type === 'title') {
      obj.title = showName;
    } else if (type === 'key' && commonUtils.isEmpty(menu.sControlName)) {
      obj.key = menu.sId;
    }
    return obj;
  };

  /**   获取父级菜单属性   */
  getMenuStatus = (menu) => {
    let { masterData } = this.props;
    const { enabled, adDisabled } = this.props;
    if (commonUtils.isEmptyObject(masterData)) {
      masterData = {};
    }
    const { bCheck, bInvalid } = masterData;
    let disabledData = []; /* 置灰按钮集合 */
    if (adDisabled) {
      disabledData = ['BtnAdd', 'BtnUpd', 'BtnDel', 'BtnSave', 'BtnCancel'];
    } else if (!adDisabled) {
      if (!enabled) {
        if (bInvalid) {
          disabledData = ['BtnUpd', 'BtnDel', 'BtnSave', 'BtnCancel', 'BtnExamine', 'BtnCancelExamine', 'BtnCopyTo', 'BtnCopyFrom', 'BtnInvalid'];
        } else if (bCheck) {
          /* 已审核查看状态 修改 删除 保存 取消 审核 复制从 取消作废置灰 */
          disabledData = ['BtnUpd', 'BtnDel', 'BtnSave', 'BtnCancel', 'BtnExamine', 'BtnCopyFrom', 'BtnCancelInvalid'];
        } else {
          /** 查看状态 修改 删除 保存 取消 审核 复制从置灰 */
          disabledData = ['BtnSave', 'BtnCancel', 'BtnCancelExamine', 'BtnCopyTo', 'BtnCopyFrom', 'BtnCancelInvalid'];
        }
      } else {
        /* 修改状态 */
        disabledData = ['BtnRefresh', 'BtnAdd', 'BtnUpd', 'BtnDel', 'BtnFirst', 'BtnPrior', 'BtnNext', 'BtnLast', 'BtnUpCheck', 'BtnDownCheck', 'BtnExamine', 'BtnCancelExamine', 'BtnCopyTo', 'BtnBsOperation', 'BtnBsOperation.BtnInvalid', 'BtnBsOperation.BtnCancelInvalid', 'BtnPrint'];
      }
    }
    return (disabledData.findIndex(item => item === menu.sControlName) > -1) || (this.props.getMenuStatus !== undefined && this.props.getMenuStatus(menu));
  };

  /**  根据二级菜单获取三级数据   */
  handleMouseEnter = (e) => {
    if (commonUtils.isNotEmptyStr(e.key)) {
      this.props.onSearchUpDownThird(e.key);
    }
  };

  /**   菜单的点击事件   */
  handleClick = (e) => {
    let obj = { enabled: false };
    const { key, keyPath } = e;
    /*   新增   */
    if (key === 'BtnAdd') { /*   增加   */
      this.handleAdd(obj);
    } else if (key === 'BtnUpd') { /*   修改   */
      this.props.onEdit(obj);
    } else if (key === 'BtnSave') { /*   保存   */
      this.props.onSubmit();
    } else if (key === 'BtnExamine') { /*   审核   */
      this.props.onBtnExamine();
    } else if (key === 'BtnCancelExamine') { /*   消审   */
      this.props.onBtnCancelExamine();
    } else if (key.indexOf('BtnBsOperation') > -1) { /*   作废、取消作废   */
      if (key === 'BtnBsOperation.BtnInvalid') {
        obj = {
          title: '确定要作废',
          handleType: 'toVoid',
        };
      } else {
        obj = {
          title: '确定要取消作废',
          handleType: 'cancel',
        };
      }
      this.props.onChangeInvalid(obj);
    } else if (key.indexOf('BtnCopyTo') > -1) { /* 复制到 */ // && commonUtils.isNotEmptyStr(e.item.props.sActiveId)
      this.props.onCopyTo(e.key, e.item.props['data-sActiveId']);
    } else if (key.indexOf('BtnCopyFrom') > -1 && commonUtils.isNotEmptyStr(e.item.props['data-sActiveId'])) { /* 复制从 */
      obj = {
        copyFromKey: key,
        copyFromSActiveId: e.item.props['data-sActiveId'],
      };
      this.props.onCopyFrom(obj);
    } else if (keyPath.indexOf('BtnUpCheck') > -1 && commonUtils.isNotEmptyStr(e.item.props['data-sActiveId']) && key.indexOf('BtnUpCheck') < 0) { /* 上查 */ /* key.indexOf('BtnUpCheck') < 0 用于防止用户点击二级菜单时的跳转 */
      this.props.onSearchUpDown(key, e.item.props['data-sActiveId']);
    } else if (keyPath.indexOf('BtnDownCheck') > -1 && commonUtils.isNotEmptyStr(e.item.props['data-sActiveId']) && key.indexOf('BtnDownCheck') < 0) { /* 下查 */ /* key.indexOf('BtnDownCheck') < 0 用于防止用户点击二级菜单时的跳转 */
      this.props.onSearchUpDown(key, e.item.props['data-sActiveId']);
    } else if (key === 'BtnNext') { /*  下一条  */
      this.props.onNext();
    } else if (key === 'BtnPrior') { /*  上一条  */
      this.props.onBtnPrior();
    } else if (key === 'BtnFirst') { /*  首条  */
      this.props.onBtnFirst();
    } else if (key === 'BtnLast') { /*  末条  */
      this.props.onBtnLast();
    } else if (key === 'BtnCancel') { /*   取消   */
      obj = {
        title: '确定要取消',
      };
      this.props.onCancel(obj);
    } else if (key.indexOf('BtnPrint') > -1 && commonUtils.isNotEmptyStr(e.item.props['data-sActiveId'])) { /*   打印   */
      this.props.onBtnPrint(e.item.props['data-sActiveId']);
    } else if (key === 'BtnDel') { /*   删除   */
      obj = {
        title: '确定要删除',
      };
      this.props.onDel(obj);
    } else if (this.props.onButtonClick !== undefined) {
      this.props.onButtonClick(key);
    }
  };

  /* 新增 */
  handleAdd = () => {
    this.props.onAdd();
  };

  /**   渲染   */
  render() {
    const { menuData, searchUpDownData } = this.state;
    /*   页面输出   */
    return (
      <div className={styles.toolBar}>
        <Menu mode="horizontal" onClick={this.handleClick}>
          { menuData.map((item) => {
            const { child, iconName, showName } = item;
            return child.length > 1 ?
              <SubMenu {...this.getMenuProps(item, 'icon')}>
                {child.map((eachChild) => {
                    if (commonUtils.isNotEmptyObject(searchUpDownData) && commonUtils.isNotEmptyArr(searchUpDownData[eachChild.sControlName])) {
                      return (
                        <MenuItemGroup {...this.getMenuProps(eachChild, 'title')}>
                          {
                            searchUpDownData[eachChild.sControlName].map((thirdMenuItem) => {
                              return (
                                <Menu.Item {...this.getMenuProps(thirdMenuItem, 'key')}>
                                  { thirdMenuItem.showName}
                                </Menu.Item>
                              );
                            })
                          }
                        </MenuItemGroup>
                      );
                    } else {
                      return (
                        <Menu.Item {...this.getMenuProps(eachChild, 'key')}>
                          {eachChild.showName}
                        </Menu.Item>
                      );
                    }
                  })}
              </SubMenu>
              : child.length === 1 ?
                <Menu.Item {...this.getMenuProps(child[0], 'key')}>
                  <Icon type={iconName} />{showName + child[0].showName}
                </Menu.Item>
              :
                <Menu.Item {...this.getMenuProps(item, 'key')}>
                  <Icon type={iconName} />{showName}
                </Menu.Item>;
          })}
        </Menu>
        <AffixMenu />
      </div>
    );
  }
}

export default ToolBarComponent;
